<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" title="出库" width="1000px" :close-on-click-modal="false" :show-close="false"
            top="50px">
            <!-- 顶部信息 -->
            <div class="order-info">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <div class="order-label">
                            <div class="order-label-title">订单类型</div>
                            <div>{{ detailData.source_type_text }}</div>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <div class="order-label">
                            <div class="order-label-title">采购单/出库退货单</div>
                            <div>{{ detailData.source_no }}</div>
                        </div>
                    </el-col>
                    <el-col :span="5">
                        <div class="order-label">
                            <div class="order-label-title">采购日期/退货日期</div>
                            <div>{{ detailData.created_at }}</div>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <div class="order-label">
                            <div class="order-label-title">供应商/客户</div>
                            <div>{{ }}</div>
                        </div>
                    </el-col>

                    <el-col :span="5">
                        <div class="order-label">
                            <div class="order-label-title">采购负责人/退货负责人</div>
                            <div>{{ detailData.contact_name }}</div>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 8px;">

                </el-row>
            </div>

            <!-- 表单部分 -->
            <el-form :model="formData" ref="formRef" :rules="rules" label-width="auto" class="form-section"
                style="margin-top: 20px;">
                <el-row :gutter="20">
                    <!-- <el-col :span="12">
                        <el-form-item label="入库仓库" prop="warehouse">
                            <el-input suffix-icon="MoreFilled" v-model="warehouseName" placeholder="" readonly
                                @click="showWarehouseDialog = true" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="入库日期" prop="out_date">
                            <el-date-picker value-format="YYYY-MM-DD" style="width: 100%;" v-model="formData.out_date"
                                type="date" placeholder="请选择" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.note" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="合库编码" prop="warehouseCode">
                            <el-input v-model="formData.warehouse_code" placeholder="根据所选仓库带出" disabled />
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row :gutter="20">


                </el-row>
            </el-form>

            <!-- 产品表格 -->
            <div class="product-section">
                <div class="product-header">
                    <span class="product-title">入库产品</span>
                </div>
                <el-table :data="formData.product_data" border style="width: 100%; margin-top: 10px;">
                    <el-table-column prop="name" label="产品名称" />
                    <el-table-column prop="specification" label="规格型号" />
                    <el-table-column prop="measure_unit_name" label="单位" />
                    <el-table-column prop="warehouse_data"
                        :label="detailData.source_type == 'purchase_return' || detailData.source_type == 'outbound_return' ? '出库仓库' : '入库仓库'"
                        width="200">
                        <template #default="scope">
                            <el-select v-model="scope.row.warehouse_id" placeholder="请选择">
                                <el-option v-for="item in scope.row.warehouse_data" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存数量" />
                    <el-table-column prop="wait_out_num" label="待出库数量" />
                    <el-table-column label="本次出库数量" width="120">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.num" :min="0" controls-position="right"
                                style="width: 100px;" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.note" placeholder="请输入" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 底部按钮 -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="submitForm">确认</el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import api from "@/api";


// 接收父组件传入的值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogType: {
        type: String,
        default: 'add'
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});

const emit = defineEmits(['update:dialogVisible', 'submit']);

// 表单ref
const formRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
    out_date: [{ required: true, message: '请选择入库时间', trigger: 'change' }],
});

interface FormData {
    id: number | string;
    out_date: string;
    note: string;
    product_data: {
        id: string | number;
        num: string | number;
        note: string;
        warehouse_id: number | string;

    }[];
}

// 表单数据
const formData = reactive<FormData>({
    "id": '', //入库ID
    "out_date": '', //入库时间
    "note": '', //备注
    "product_data": [
        {
            "id": '',
            "warehouse_id": '',
            "num": '',
            "note": "备注"
        },

    ]

});

// 监听对话框显示状态
const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => {
        emit('update:dialogVisible', val);
    }
});

// 监听props变化
watch(() => props.dialogVisible, (newVal) => {
    if (newVal) {
        // 打开弹窗时，初始化表单数据
        initFormData();
    } else {
        formData.product_data = []
        formData.id = ''
        formData.out_date = ''
        formData.note = ''
    }
});

interface DetailData {
    type: string;
    code: string;
    created_at: string;
    manager_name: string;
    supplier_name: string;
    customer_name: string;
    source_type_text: string;
    source_no: string;
    source_date: string;
    source_type: string;
    contact_name: string;
}

let detailData = ref<DetailData>({
    type: '1',
    code: '',
    created_at: '',
    manager_name: '',
    supplier_name: '',
    customer_name: '',
    source_type_text: '',
    source_no: '',
    source_date: '',
    source_type: '',
    contact_name: '',
});

const warehouseList = ref([

]);
// 初始化表单数据
const initFormData = async () => {
    // 清空表单
    Object.keys(formData).forEach(key => {
        if (key !== 'products') {
            formData[key] = '';

        }
    });

    const res = await api.product.warehouse_product_out_detail({
        id: props.dialogRow.id
    });

    if (res.code == 200) {
        formData.id = res.data.id;
        detailData.value = res.data;
        console.log(res.data, 'res.data');

        formData.product_data = res.data.product_data.map((item: any) => {
            if (!('num' in item)) {
                item.num = 0
            }
            if (!('warehouse_id' in item)) {
                item.warehouse_id = item.warehouse_data.length > 0 ? item.warehouse_data[0].id : ''
            }

            return item
        })

    }

    //获取仓库列表
    const resData = await api.publicFun.getWarehouseList({ type: 1 });
    if (resData.code == 200) {
        warehouseList.value = resData.data;
    }
};

// 提交表单
// 提交表单
const submitForm = async () => {
    // 判断是否是采购单/退货单
    if (!formRef.value) return;

    //出库仓库必须选择
    if (!formData.product_data.some((item: any) => item.warehouse_id)) {
        ElMessage.error('出库仓库必须选择');
        return;
    }
    //表格备注必填
    // if (!formData.product_data.some((item: any) => item.note)) {
    //     ElMessage.error('表格备注必须填写');
    //     return;
    // }
    // 入库日期必填
    if (!formData.out_date) {
        ElMessage.error('入库日期必填');
        return;
    }

    // 创建提交数据副本，避免修改原始数据
    const submitProductData = formData.product_data.map((item: any) => {
        return {
            "id": item.product_id,
            "warehouse_id": item.warehouse_id,
            "num": item.num,
            "note": item.note
        }
    });

    try {
        // await formRef.value.validate();
        const res = await api.product.warehouse_product_out_out({
            ...formData,
            product_data: submitProductData  // 使用副本数据提交
        });
        console.log(formData, 'formData');
        if (res.code == 200) {
            ElMessage.success('入库成功');
            dialogVisible.value = false;
            emit('submit');
        } else {
            ElMessage.error(res.msg || '入库失败');
        }

    } catch (error) {
        console.error('表单提交错误', error);
        // ElMessage.error('请检查表单填写是否正确');
    }
};


</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 10px !important;
}

::v-deep .form-section {
    padding-top: 0px !important;
}

::v-deep .el-form-item__label {
    margin-left: 0px !important;
}

::v-deep .el-form-item__label-wrap {
    margin-left: 0px !important;
}

::v-deep .el-form-item {
    display: block;
}


:deep(.el-dialog) {
    --el-dialog-padding-primary: 0px;
}

:deep(.el-dialog__header) {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

:deep(.dialog-footer) {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #000;
}

:deep(.el-dialog__body) {
    padding: 20px 10px;
    padding-right: 30px;
}

.order-info {
    background: #f7f8fa;
    padding: 12px 20px 4px 20px;
    border-radius: 4px;
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
}

.form-section {
    background: #fff;
    padding: 20px 20px 0 20px;
    border-radius: 4px 4px 0 0;
}

.product-section {
    background: #fff;
    padding: 20px;
    padding-bottom: 0px;
    border-radius: 0 0 4px 4px;
}

.product-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;
}

.product-title {
    font-weight: bold;
    font-size: 16px;
    border-left: 3px solid #3a5fff;
    padding-left: 8px;
}

.dialog-footer {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
    text-align: right;
}

.order-label {
    .order-label-title {
        color: #999;
        font-size: 13px;
        margin-bottom: 2px;
    }

    div:last-child {
        color: #333;
        font-size: 15px;
        font-weight: 500;
    }
}

:deep(.el-form-item__label) {
    font-weight: 500;
}
</style>
